package com.nidu.demo.post.executor.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.company.gateway.CompanyGateway;
import com.nidu.demo.company.model.Company;
import com.nidu.demo.post.convertor.PositionConvertor;
import com.nidu.demo.post.convertor.PositionCriteriaConvertor;
import com.nidu.demo.post.dto.PositionCO;
import com.nidu.demo.post.dto.PositionListQry;
import com.nidu.demo.post.gateway.PositionGateway;
import com.nidu.demo.post.model.Position;
import com.nidu.demo.post.model.PositionCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 职位列表查询执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class PositionListQryExe {

    private final PositionGateway gateway;

    private final PositionConvertor convertor;

    private final PositionCriteriaConvertor criteriaConvertor;

    private final CompanyGateway companyGateway;

    public MultiResponse<PositionCO> execute(PositionListQry qry) {
        PositionCriteria criteria = criteriaConvertor.toDataObject(qry);
        List<Position> posts = gateway.listByCondition(criteria);
        if(CollUtil.isEmpty(posts)){
            throw new BizException(ErrorCodeConstants.POSITION_NOT_FOUND.getCode(), ErrorCodeConstants.POSITION_NOT_FOUND.getMessage());
        }
        List<PositionCO> postCOS = convertor.toClientObjects(posts);

        Set<Long> companyIds = postCOS.stream().map(PositionCO::getCompanyId).collect(Collectors.toSet());
        if(!CollUtil.isEmpty(companyIds)){
            List<Company> companyList = companyGateway.getByIds(companyIds);
            Map<Long, Company> companyMap = companyList.stream().collect(Collectors.toMap(Company::getId, Function.identity()));
            postCOS.forEach(item -> item.setCompanyName(companyMap.get(item.getCompanyId()).getCompanyName()));
        }

        return MultiResponse.of(postCOS);
    }

}